package fastjsonDemo.JSONDemo;

import com.alibaba.fastjson.JSON;
import fastjsonDemo.JSONDemo.pojo.User;
import org.junit.Test;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * toJSONString  对象转json
 * parseObject  json转对象
 * parseArray  json转数组, 如果想数组转json也是用toJSONString
 */
public class ObjectAndJSON {

	static User user;

	static {
		user = new User();
		user.setName("校长");
		user.setAge(3);
		user.setSalary(new BigDecimal("123456789.0123"));
	}

	/**
	 * 对象和json互相转换
	 */
	@Test
	public void javaBeanAndJSON() {
		/*对象转json*/
		String jsonString = JSON.toJSONString(user);
		System.out.println(jsonString);
		// 输出 {"age":3,"name":"校长","old":false,"salary":123456789.0123}

		/*json转对象*/
		User user1 = JSON.parseObject(jsonString, User.class);
		System.out.println(user1); //User{name='校长', age=3, salary=123456789.0123}

	}

	/**
	 * json转数组
	 */
	@Test
	public void arrayObjectAndJson() {

		String jsonStringArray = "[{\"age\":3,\"birthdate\":1496738822842,\"name\":\"校长\",\"old\":true,\"salary\":123456789.0123},{\"age\":5," +
				"\"birthdate\":1496738822842,\"name\":\"学生\",\"old\":true,\"salary\":123456789.0123}]";
		/*json转数组*/
		List<User> userList = JSON.parseArray(jsonStringArray, User.class);
		System.out.println(userList.size());    // 输出 2
		System.out.println(userList);//[User{name='校长', age=3, salary=123456789.0123}, User{name='学生', age=5, salary=123456789.0123}]
		//数组转json
		String s = JSON.toJSONString(userList);
		System.out.println("s = " + s); //[{"age":3,"name":"校长","salary":123456789.0123},{"age":5,"name":"学生","salary":123456789.0123}]
	}

	/**
	 * 基本数据类型数组
	 */
	@Test
	public void arrayBaseTypeAndJson() {
		int[] arr = {1, 2, 3, 4, 5, 6, 7};
		String jsonString = JSON.toJSONString(arr);
		System.out.println("jsonString = " + jsonString);//jsonString = [1,2,3,4,5,6,7]

		//转成了集合了
		List<Integer> integers = JSON.parseArray(jsonString, Integer.class);
		System.out.println("integers = " + integers);
	}

	/**
	 * 对象和Map互相转换
	 */
	@Test
	public void MapAndJavaBean() {
		User user = new User();
		user.setName("校长");
		user.setAge(3);
		user.setSalary(new BigDecimal("123456789.0123"));
		/*对象转map*/
		String jsonString1 = JSON.toJSONString(user);
		Map map = JSON.parseObject(jsonString1, Map.class);
		System.out.println("map = " + map);// map = {name=校长, salary=123456789.0123, age=3}

		String jsonString = JSON.toJSONString(map);
		User user1 = JSON.parseObject(jsonString, User.class);//json转对象
		System.out.println("user1 = " + user1); //user1 = User{name='校长', age=3, salary=123456789.0123}


	}


}
